import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parse
from bs4 import BeautifulSoup
import random
import time


# 签名
def sign(secret, timestamp):
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    sign_str = {"sign": sign, "timestamp": timestamp}
    return sign_str


# 钉钉消息
def send_msg(webhook,sign, timestamp,message):
    tim = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    headers = {"Content-Type": "application/json"}
    readData = EveryDayStudy()
    # imgurl = getImgUrl()
    data = {
        "msgtype": "markdown",
        "markdown": {
            "title": "接口自动化",
            # "text": "#### 今日份浓汤  \n> " + readData + " \n\n> ![screenshot](" + "imgurl" + ") \n> ###### " + tim + " [更多](http://www.duanmeiwen.com/yulu/lizhi/46345.html) \n"
            "text":message
        },
        # @群内人员
        "at": {
            "atMobiles": [

            ],
            "atUserIds ": [

            ],
            "isAtAll": True
        }
    }
    webh = webhook + '&timestamp=' + timestamp + '&sign=' + sign
    r = requests.post(webh, data=json.dumps(data), headers=headers)
    print(r.text)


# 每日一读 文字
def EveryDayStudy():
    num = random.randint(1, 200)
    res = requests.get('http://www.duanmeiwen.com/yulu/lizhi/46345.html')
    res.encoding = 'gb2312'
    bs = BeautifulSoup(res.text, "html.parser")

    Datalist = []
    for i in bs.find_all("div", class_="content"):
        text1 = i.text
        for j in range(1, 300, 1):
            text2 = text1.split(str(j) + '、')
            text3 = text2[1].split(str(j + 1) + '、')
            Datalist.append(text3[0])
        return Datalist[num]


if __name__ == '__main__':

    # 时间戳
    # timestamp = str(round(time.time() * 1000))
    # # 钉钉机器人配置
    # secret = 'SEC6e09a5f5c82e2a93735d5{test}c48ec374407faedef1516158ae46d080b2865e8d8c0'
    # webhook = 'https://oapi.dingtalk.com/robot/send?access_token=10406f2ba196fd33d683c866c8e4512b6187de8feadbe4892d53ef88f1d94196'
    # sign_str = sign(secret, timestamp)
    # sg = sign_str['sign']
    # send_msg(sg, timestamp,)
    pass
